package com.heima.gateway.filter;

import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Service
public class AuthFilter implements GlobalFilter, Ordered {

    /**
     * 过滤器执行的逻辑
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //从请求对象中获取请求路径
        String path = request.getURI().getPath();
        //判断路径中是否包含login
        if (path.contains("/login")){
            //包含的话就放行
            return chain.filter(exchange);
        }
        //从请求对象中获取请求头
        String token = request.getHeaders().getFirst("token");
        //不包含的话 需要鉴权 判断请求头中是否有token
        //没有token 返回401未授权
        if (StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();

        }
        //如果有token 需要验证token是否有效
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            int i = AppJwtUtil.verifyToken(claimsBody);//验证是否有效
            //无效 返回401未授权
            //有效的话 在token中提取id
            if (i == -1 || i == 0){
                Object userId = claimsBody.get("id");
                //将用户返回到请求头中 将带有id的token转发到后端微服务中 放行
                request.mutate().header("userId",userId.toString());
                return chain.filter(exchange); //放行
            }
        }catch (Exception e){
            //记录日志异常 过期
            log.error(e.getMessage());
        }
        //设置返回状态
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //响应给客户端，不再往后端转发
        return response.setComplete();
    }

    /**
     * 过滤器执行的顺序 数值越小，优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
